import moment from "moment";
import { DateRound } from "@/utils/VEnum";

/**
 * 随机整数
 */
export function IntegerRandom(min: number = 0, max: number): Number {
  return Math.floor(Math.random() * (max - min)) + min;
}

/**
 * sleep
 * @param time timestamp
 */
export function SleepSync<Number>(time: number = 100): Promise<void> {
  return new Promise((resolve: any) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
}

/**
 * 深拷贝
 *
 * @export
 * @param {*} object
 * @returns {*}
 */
export function CloneDeep<T>(object: T): any {
  return JSON.parse(JSON.stringify(object));
}

/**
 * remove Object key/value for value is undefined
 *
 * @export
 * @template T
 * @returns {*}
 */
export function ObjectToCleanUndefined<T extends any>(target: T): any {
  const cache: any = {};
  for (const key in target) {
    if (target.hasOwnProperty(key)) {
      const val = target[key];
      if (key == "startTime" || key == "endTime") {
        const _keys: any = {
          startTime: DateRound.START,
          endTime: DateRound.END
        };
        const _date = FmtDate(val, _keys[key]);
        if (_date) cache[key] = _date;
      } else if (val || val == 0) {
        if (val !== "") cache[key] = val;
      }
    }
  }
  return cache;
}

/**
 *formate date
 *
 * @export
 * @template T
 * @param {T} date
 * @returns {string}
 */
export function FmtDate<T extends any>(
  date: T,
  tail?: DateRound,
  format: string = "YYYY-MM-DD"
): string {
  if (!date) return "";
  let tailStr: string = "";
  if (tail) {
    tailStr = " " + (tail == DateRound.START ? "00:00:00" : "23:59:59");
  }
  const _date = moment(date).format(format);
  return _date + tailStr;
}

const DateConf = {
  ALlDay: 60 * 60 * 24, // => 86400 秒;
  AllHour: 60 * 60, //3600秒
  ALlMin: 60 //60秒
};
/**
 *
 * @param day
 * @param hour
 * @param min
 */
export function DayHourMinToTimes(
  day: number,
  hour: number,
  min: number
): number {
  const { ALlDay, AllHour, ALlMin }: any = DateConf;
  return day * ALlDay + hour * AllHour + min * ALlMin;
}

export function TimesToDayHourMin(timestamp: number) {
  const days = timestamp / 60 / 60 / 24;
  const daysRound = Math.floor(days);
  const hours = timestamp / 60 / 60 - 24 * daysRound;
  const hoursRound = Math.floor(hours);
  const minutes = timestamp / 60 - 24 * 60 * daysRound - 60 * hoursRound;
  const minutesRound = Math.floor(minutes);
  return [daysRound, hoursRound, minutesRound];
}
